<script setup lang="ts">
import { ref,onMounted,onUpdated } from 'vue'
import * as Y from 'yjs'
import { WebsocketProvider } from 'y-websocket'
import { QuillBinding } from 'y-quill'
import Quill from 'quill'
import QuillCursors from 'quill-cursors'
import '../../../node_modules/quill/dist/quill.snow.css'
// import '../../../node_modules/quill/dist/quill.bubble.css'

let isShow = ref(false);

let isInit=false;

let showView=()=>{
    if(isInit){
        return;
    }
    isInit=true;

    Quill.register('modules/cursors', QuillCursors)

    const quill = new Quill(document.querySelector('#editor5'), {
    modules: {
        cursors: true,
        toolbar: [
        // adding some basic Quill content features
        [{ header: [1, 2, false] }],
        ['bold', 'italic', 'underline'],
        ['image', 'code-block']
        ],
        history: {
        // Local undo shouldn't undo changes
        // from remote users
        userOnly: true
        }
    },
    placeholder: 'Start collaborating...',
    theme: 'snow' // snow,'bubble' is also great
    })

    // A Yjs document holds the shared data
    const ydoc = new Y.Doc()

    // connect to the public demo server (not in production!)
    const provider = new WebsocketProvider(
        'ws://localhost:1234', 'quill-editor-room-1', ydoc
    )
    provider.on('status', event => {
        console.log(`ws status:${event.status}`) // logs "connected" or "disconnected"
    })

    // Define a shared text type on the document
    const ytext = ydoc.getText('quill')

    // "Bind" the quill editor to a Yjs text type.
    const binding = new QuillBinding(ytext, quill, provider.awareness)

    // Remove the selection when the iframe is blurred
    window.addEventListener('blur', () => { quill.blur() })
}

onMounted(()=>{
    
})

onUpdated(()=>{
    if(isShow.value==true){
        showView();
    }
})

</script>

<template>
    <div class="hide"><input type="button" :value="`${isShow ? 'hide' : 'show'} yjs 5`" @click="isShow = !isShow"></div>
    <div v-show ="isShow">
        <div class="desc">Y JS 示例 ：Quill 编辑器集成 + Y-WebSocket,需要执行 yarn run websocket</div>
        <div id="editor5" class="editor"></div>
    </div>
</template>

<style scoped>
/* @import './styles/katex.min.css'; */
/* @import './styles/monokai-sublime.min.css'; */

.editor{
    width:600px;
    height:400px;
}
</style>